package cn.edu.zut.hkxy.controller;

import cn.edu.zut.hkxy.pojo.Admin;
import cn.edu.zut.hkxy.pojo.AjaxResult;
import cn.edu.zut.hkxy.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
public class PageController {
    @Autowired
    private UsersService usersService;
    @Autowired
    private TotalService totalService;

    @RequestMapping("/index")
    public String toindex(){
        return "index";
    }
    @RequestMapping("/login")
    public String toLogin(HttpSession session){
        if(session.getAttribute("admin")!=null){
            return "/index";
        }else {
            return "login";
        }
    }

    @RequestMapping("/dologin")
    public String doLogin(Admin admin, HttpSession session, HttpServletRequest request) {
        Admin a;
        try {
            if (usersService.findUsername(admin.getUsername())) {
                //用户名存在
                a = usersService.usernameLogin(admin.getUsername(), admin.getPassword());
                System.out.println(a);
                if (a != null) {
                    //用户密码正确返回主页
                    session.setAttribute("admin", a);
                    return "redirect:/index";
                } else {
                    //密码不正确
                    System.out.println("密码不正确");
                    request.setAttribute("msg","密码不正确");
                    return "/login";
                }
            } else {
                //用户名不存在
                System.out.println("用户名不存在");
                request.setAttribute("msg","用户名不存在");
                return "/login";
            }
        } catch (Exception e) {
            //后台异常
            System.out.println("服务异常，请联系管理员");
            request.setAttribute("msg","服务异常，请联系管理员");
            return "/login";
        }
    }

    @RequestMapping("/doLogout")
    public String doLogout(HttpSession session){
        session.invalidate();
        return "redirect:/login";
    }

    @RequestMapping("/article-count-json")
    @ResponseBody
    public AjaxResult getCount(){
        AjaxResult ajaxResult=new AjaxResult();
        try {
            ajaxResult.setData(totalService.getCount());
            ajaxResult.setCode(AjaxResult.RESULT_SUCCESS_CODE);
        }catch (Exception e){
            ajaxResult.setCode(AjaxResult.RESULT_ERROR_CODE);
            ajaxResult.setMessage(e.getMessage());
        }finally {
            return ajaxResult;
        }
    }
}
